package com.wqh.article.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheKey;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.wqh.article.entity.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @author wanqh
 * @date 2018/01/09 16:39
 * @description:
 */
@Service
public class ArticleService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand
    @CacheResult
    public User getUserById(@CacheKey("id") Long id) {
        return restTemplate.getForObject("http://USER-SERVICE/user/{1}", User.class, id);
    }

    private String getCacheKey(Long id) {
        return String.valueOf(id);
    }

    @CacheRemove(commandKey = "getUserById")
    public User update(@CacheKey("id")User user){
        return  restTemplate.postForEntity("http://USER-SERVICE/u/update", user, User.class).getBody();
    }

    public List<User> findUserByIds(List<Long> ids){
        System.out.println("findUserByIds---------"+ids+"Thread.currentThread().getName():" + Thread.currentThread().getName());
        String str = StringUtils.join(ids,",");
        User[] users =  restTemplate.getForObject("http://USER-SERVICE/users/ids?ids={1}", User[].class,str);
        return Arrays.asList(users);
    }


    @HystrixCollapser(batchMethod = "findAll",collapserProperties = {
            @HystrixProperty(name = "timerDelayInMilliseconds",value = "100")
    })
    public Future<User> findOne(Long id){
        return null;
    }
    @HystrixCommand
    public List<User> findAll(List<Long> ids){
        System.out.println("findUserByIds---------"+ids+"Thread.currentThread().getName():" + Thread.currentThread().getName());
        String str = StringUtils.join(ids,",");
        User[] users =  restTemplate.getForObject("http://USER-SERVICE/users/ids?ids={1}", User[].class,str);
        return Arrays.asList(users);
    }
}
